package com.example.springboot.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.example.springboot.common.Result;
import com.example.springboot.entity.ExportProduct;
import com.example.springboot.entity.Product;
import com.example.springboot.service.ProductService;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/*
 * 功能：文件的上传下载
 * 1.批量导入产品信息
 * 2.批量导出
 * 日期：2024-3-31 9:10
 * 作者：RabbitQ
 */
@CrossOrigin
@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    ProductService productService;

    /*批量导入产品信息——认证任务
    * 传入excel文件，导入数据库
    * */
    @PostMapping("/inputMulti")
    public Result inputMulti(MultipartFile file) throws IOException {
        //使用hu-tool中的类读取字节流
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        //Product输入信息中的开始时间还没有设置——在service层中获取当前时间-每个都加上
        List<Product> productList = reader.readAll(Product.class);

        //写入数据库
        try{
            //批量录入
            productService.submitBatch(productList);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("数据导入错误，请检查数据格式或是否有重复数据");
        }
        return Result.success();
    }

    //第三方认证——批量导出
    @GetMapping("/exportThird")
    public Result exportThird(HttpServletResponse response) throws IOException {
        List<ExportProduct> productThird = new ArrayList<>();
        productThird = productService.selectEvenIDThird();

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("第三方认证数据", "utf-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition","attachment; filename="+ fileName + ".xlsx");

        EasyExcel.write(response.getOutputStream())
        .head(ExportProduct.class)
        .excelType(ExcelTypeEnum.XLSX)
        .sheet("第三方认证数据")
        .doWrite(productThird);

        return Result.success();
    }


    //上传签名图片

    @PostMapping("/uploadSignature")
    public String uploadSignature(MultipartFile fileSig) {
        //图片检验
        if(fileSig.isEmpty()){
            return "图片上传失败";
        }

        //file重命名
        String originalName = fileSig.getOriginalFilename();
        String ext = "." + originalName.split("\\.")[1]; //获取文件后缀

        String uuid = UUID.randomUUID().toString().replace("-", "");
        String fileName = uuid + ext;

        //上传图片
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        String pre = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath()
                + "\\src\\main\\resources\\static\\signatureImages\\";

        System.out.println(pre);

        String filePath = pre + fileName;

        try {
            fileSig.transferTo(new File(filePath));
            //return filePath + "  " + "上传成功！";

            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "图片上传失败";
    }


}
